# encoding=utf-8

import requests
import json

API_key = "你创建应用的API Key"
secret_key = "你创建应用的Secret Key"
access_token_url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_key}&client_secret={secret_key}"

# 获取token
response = requests.get(access_token_url)
print(response.json())
access_token = response.json()["access_token"]		# access_token即为我们需要的token


post_url = "https://aip.baidubce.com/rpc/2.0/aasr/v1/create"
file_url = "你的音频文件的url"
body = {
	"speech_url": file_url,		# 音频url
	"format": "mp3",			# 音频格式
	"pid": 1537,				# 中文
	"rate": 16000,				# 采样率	[16000] 固定值
}
token = {"access_token": access_token}		# 上一步获得的token

# 生成转写任务
rep = requests.post(post_url, params=token, data=json.dumps(body))
print(rep.json())
task_id = rep.json()["task_id"]		# 获得我们需要的task_id


query_url = "https://aip.baidubce.com/rpc/2.0/aasr/v1/query"
query_body = {
	"task_ids": [task_id]
}

# 查询转写任务是否完成
rep = requests.post(query_url, params=token, data=json.dumps(query_body))
print(json.dumps(rep.json()))
with open("feed.json","w") as f:
	json.dump(rep.json(), f)
task_info = rep.json()["tasks_info"]["task_result"]["result"]       # 成功了的话此变量即为我们需要的所有文字
